package com.nlp.visualization.service.tasks;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.RecursiveAction;

import static com.nlp.visualization.common.CONSTANTS.TASK_MAX;

/**
 * 微博json处理的任务
 */
public class WeiboJsonPreProcessTask extends RecursiveAction {

    Logger logger = LoggerFactory.getLogger(WeiboJsonPreProcessTask.class);
    // 每个"小任务"最多只50个数
    private static final int MAX = TASK_MAX;

    private int start;
    private int end;
    private List<String> lines;


    public WeiboJsonPreProcessTask(int start, int end, List lines) {
        this.start = start;
        this.end = end;
        this.lines = lines;
    }

    @Override
    protected void compute() {
        // 当end-start的值小于MAX时候，开始执行任务
        if ((end - start) < MAX) {
            for (int i = start; i < end; i++) {
                //第一处更改的地方：Object中不能带没有转义的引号
                if (lines.get(i).indexOf("ObjectId(") != -1) {
                    lines.set(i, lines.get(i).replace("ObjectId(", "\"ObjectId(\\"));
                    lines.set(i, lines.get(i).replace("\")", "\\\")\""));
                }
            }
        } else {
            // 将大任务分解成两个小任务
            int middle = (start + end) / 2;
            WeiboJsonPreProcessTask left = new WeiboJsonPreProcessTask(start, middle, lines);
            WeiboJsonPreProcessTask right = new WeiboJsonPreProcessTask(middle, end, lines);
            // 并行执行两个小任务
            left.fork();
            right.fork();
        }
    }
}
